using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Windows;
using System.Windows.Input;
using System.Windows.Controls;  // 添加WPF控件引用
using System.Xml.Linq;
using Prism.Commands;
using System.Windows.Forms;  // 保留用于FolderBrowserDialog
using MessageBox = System.Windows.MessageBox;  // 明确指定MessageBox类型
using System.Net.Http;
using Newtonsoft.Json;
using System.Threading.Tasks;
using Prism.Mvvm;
using TranslateCheckerTool.Models;

namespace TranslateCheckerTool.ViewModels
{
    public class MainWindowViewModel : BindableBase
    {
        private ObservableCollection<TranslationItem> _translationItems;
        public ObservableCollection<TranslationItem> TranslationItems
        {
            get => _translationItems;
            set => SetProperty(ref _translationItems, value);
        }

        private ObservableCollection<FileItem> _fileItems;
        public ObservableCollection<FileItem> FileItems
        {
            get => _fileItems;
            set => SetProperty(ref _fileItems, value);
        }

        private FileItem _selectedFile;
        public FileItem SelectedFile
        {
            get => _selectedFile;
            set
            {
                if (SetProperty(ref _selectedFile, value))
                {
                    LoadTranslationItems();
                }
            }
        }
        public DelegateCommand<FileItem> SelectFileCommand { get; }
        public ICommand SelectFolderCommand { get; }
        public ICommand SaveCommand { get; }
        public ICommand TranslateCommand { get; }
        public ICommand BatchTranslateCommand { get; }

        private bool _isTranslating;
        public bool IsTranslating
        {
            get => _isTranslating;
            set => SetProperty(ref _isTranslating, value);
        }

        // 百度翻译API配置
        private const string BAIDU_APP_ID = "20240705002092238";
        private const string BAIDU_SECRET_KEY = "C0hl_r5oKcgUB4jILP8G";

        public MainWindowViewModel()
        {
            _translationItems = new ObservableCollection<TranslationItem>();
            _fileItems = new ObservableCollection<FileItem>();
            SelectFileCommand = new DelegateCommand<FileItem>(SelectFileHandler);
            SelectFolderCommand = new DelegateCommand(SelectFolder);
            SaveCommand = new DelegateCommand(Save);
            TranslateCommand = new DelegateCommand<TranslationItem>(async item => await TranslateItemAsync(item));
            BatchTranslateCommand = new DelegateCommand(async () => await BatchTranslateAsync());

            // 自动加载默认目录
            LoadDefaultDirectory();
        }

        private bool CheckSaveBeforeSwitch()
        {
            if (TranslationItems.Any(item => item.IsModified))
            {
                var result = System.Windows.MessageBox.Show("当前文件有未保存的修改，是否保存？",
                    "提示", System.Windows.MessageBoxButton.YesNoCancel);

                if (result == System.Windows.MessageBoxResult.Yes)
                {
                    Save();
                }
                else if (result == System.Windows.MessageBoxResult.Cancel)
                {
                    return false;
                }
            }
            return true;
        }

        private void SelectFileHandler(FileItem item)
        {
            try
            {
                if (item == null || !File.Exists(item.Path)) return;
                if (!CheckSaveBeforeSwitch()) return;

                SelectedFile = item;
                foreach (var ti in TranslationItems)
                {
                    ti.OriginalChinese = ti.ChineseText;
                    ti.OriginalEnglish = ti.EnglishText;
                }
                TranslationItems.Clear();
                var zhDoc = XDocument.Load(item.Path);
                var enPath = item.Path.Replace("\\zh-CN\\", "\\en-US\\");
                XDocument? enDoc = null;
                if (File.Exists(enPath))
                {
                    enDoc = XDocument.Load(enPath);
                }

                //var ns = zhDoc.Root?.GetDefaultNamespace();
                var ns = "clr-namespace:System;assembly=mscorlib";
                if (ns == null) return;
                //var elements = zhDoc.Elements().ToList();
                var elements = zhDoc.Descendants().ToList();

                foreach (var element in elements)
                {
                    if (element.Name.LocalName != "String") continue;
                    var key = element.Attribute(XName.Get("Key", "http://schemas.microsoft.com/winfx/2006/xaml"))?.Value;
                    if (string.IsNullOrEmpty(key)) continue;

                    var zhText = element.Value;
                    var enText = string.Empty;

                    if (enDoc != null)
                    {
                        var enElement = enDoc.Descendants().Where(e => e.Name.LocalName == "String")
                            .FirstOrDefault(e => e.Attribute(XName.Get("Key", "http://schemas.microsoft.com/winfx/2006/xaml"))?.Value == key);
                        if (enElement != null)
                        {
                            enText = enElement.Value;
                        }
                    }

                    TranslationItems.Add(new TranslationItem
                    {
                        Key = key,
                        ChineseText = zhText,
                        EnglishText = enText
                    });
                }
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.Message);
            }
        }

        private void LoadDefaultDirectory()
        {
            string defaultPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Languages", "zh-CN");
            if (Directory.Exists(defaultPath))
            {
                LoadDirectory(defaultPath);
            }
        }

        private void SelectFolder()
        {

            using (var dialog = new FolderBrowserDialog())
            {
                dialog.Description = "选择Language文件夹下的zh-CN文件夹";
                if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    LoadDirectory(dialog.SelectedPath);
                }
            }
        }

        private void LoadDirectory(string path)
        {
            FileItems.Clear();
            var rootItem = new FileItem { Name = Path.GetFileName(path), Path = path };
            LoadDirectoryRecursive(rootItem, path,1);
            FileItems.Add(rootItem);
        }

        private void LoadDirectoryRecursive(FileItem parentItem, string path,int level)
        {
            foreach (var dir in Directory.GetDirectories(path))
            {
                var dirItem = new FileItem { Name = Path.GetFileName(dir), Path = dir };
                parentItem.Children.Add(dirItem);
                LoadDirectoryRecursive(dirItem, dir,level+1);
                if (level > 1)
                {
                    parentItem.IsExpanded = false;
                }
                else
                {
                    parentItem.IsExpanded = true;
                }
            }

            foreach (var file in Directory.GetFiles(path, "*.xaml"))
            {
                parentItem.Children.Add(new FileItem { Name = Path.GetFileName(file), Path = file });
            }
        }

        private void LoadTranslationItems()
        {
            if (SelectedFile == null || !File.Exists(SelectedFile.Path)) return;

            TranslationItems.Clear();
            var zhDoc = XDocument.Load(SelectedFile.Path);
            var enPath = SelectedFile.Path.Replace("\\zh-CN\\", "\\en-US\\");
            XDocument? enDoc = null;
            if (File.Exists(enPath))
            {
                enDoc = XDocument.Load(enPath);
            }

            var ns = zhDoc.Root?.GetDefaultNamespace();
            if (ns == null) return;

            foreach (var element in zhDoc.Descendants(ns + "String"))
            {
                var key = element.Attribute(XName.Get("Key", "http://schemas.microsoft.com/winfx/2006/xaml"))?.Value;
                if (string.IsNullOrEmpty(key)) continue;

                var zhText = element.Value;
                var enText = string.Empty;

                if (enDoc != null)
                {
                    var enElement = enDoc.Descendants(ns + "String")
                        .FirstOrDefault(e => e.Attribute(XName.Get("Key", "http://schemas.microsoft.com/winfx/2006/xaml"))?.Value == key);
                    if (enElement != null)
                    {
                        enText = enElement.Value;
                    }
                }

                TranslationItems.Add(new TranslationItem
                {
                    Key = key,
                    ChineseText = zhText,
                    EnglishText = enText
                });
            }
        }

        private async Task TranslateItemAsync(TranslationItem item)
        {
            if (item == null || IsTranslating) return;

            try
            {
                IsTranslating = true;
                var translatedText = await TranslateText(item.ChineseText);
                if (!string.IsNullOrEmpty(translatedText))
                {
                    var result = MessageBox.Show($"覆盖当前翻译内容？\n原文：{item.ChineseText}\n译文：{translatedText}",
                        "确认翻译", MessageBoxButton.YesNo, MessageBoxImage.Question);
                    if (result == MessageBoxResult.Yes)
                    {
                        item.EnglishText = translatedText;
                        item.IsModified = true; // 标记修改状态
                    }
                }
            }
            catch (HttpRequestException hex)
            {
                MessageBox.Show($"网络错误: {hex.Message}\n请检查网络连接", "翻译错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            catch (JsonException jex)
            {
                MessageBox.Show($"解析翻译结果失败: {jex.Message}", "数据错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"翻译失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                IsTranslating = false;
            }
        }

        private async Task BatchTranslateAsync()
        {
            if (IsTranslating || TranslationItems.Count == 0) return;

            var confirm = MessageBox.Show("批量翻译将覆盖现有内容，是否继续？",
                "警告", MessageBoxButton.OKCancel, MessageBoxImage.Warning);
            if (confirm != MessageBoxResult.OK) return;

            try
            {
                IsTranslating = true;
                var progressWindow = new Window
                {
                    Title = "正在批量翻译...",
                    Width = 300,
                    Height = 100,
                    WindowStartupLocation = WindowStartupLocation.CenterScreen,
                    Content = new StackPanel
                    {
                        Orientation = System.Windows.Controls.Orientation.Vertical,
                        VerticalAlignment = VerticalAlignment.Center,
                        Children =
                        {
                            new System.Windows.Controls.ProgressBar { IsIndeterminate = true, Height = 20 },
                            new TextBlock { Text = "正在翻译，请稍候...", Margin = new Thickness(0,10,0,0) }
                        }
                    }
                };
                progressWindow.Show();

                int translatedCount = 0;
                foreach (var item in TranslationItems)
                {
                    try
                    {
                        item.EnglishText = await TranslateText(item.ChineseText);
                        item.IsModified = true;
                        translatedCount++;
                        await Task.Delay(200); // 降低请求频率避免被API限制
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"翻译 {item.Key} 失败: {ex.Message}",
                            "错误", MessageBoxButton.OK, MessageBoxImage.Warning);
                    }
                }

                progressWindow.Close();
                MessageBox.Show($"批量翻译完成，成功 {translatedCount}/{TranslationItems.Count} 条",
                    "完成", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch (HttpRequestException hex)
            {
                MessageBox.Show($"网络连接异常: {hex.Message}",
                    "网络错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"批量翻译失败: {ex.Message}",
                    "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                IsTranslating = false;
            }
        }

        private async Task<string> TranslateText(string text)
        {
            if (string.IsNullOrWhiteSpace(text)) return string.Empty;

            try
            {
                using var httpClient = new HttpClient();
                var salt = DateTime.Now.Millisecond.ToString();
                var sign = GenerateMD5(BAIDU_APP_ID + text + salt + BAIDU_SECRET_KEY);

                var response = await httpClient.PostAsync("https://fanyi-api.baidu.com/api/trans/vip/translate",
                    new FormUrlEncodedContent(new Dictionary<string, string>
                    {
                        {"q", text},
                        {"from", "zh"},
                        {"to", "en"},
                        {"appid", BAIDU_APP_ID},
                        {"salt", salt},
                        {"sign", sign}
                    }));

                response.EnsureSuccessStatusCode();

                var result = JsonConvert.DeserializeObject<BaiduTranslationResult>(
                    await response.Content.ReadAsStringAsync());

                return string.Join(" ", result?.TransResult.Select(t => t.Dst) ?? Array.Empty<string>());
            }
            catch (Exception ex)
            {
                MessageBox.Show($"翻译错误: {ex.Message}");
                return string.Empty;
            }
        }

        private string GenerateMD5(string input)
        {
            using var md5 = System.Security.Cryptography.MD5.Create();
            byte[] inputBytes = System.Text.Encoding.UTF8.GetBytes(input);
            byte[] hashBytes = md5.ComputeHash(inputBytes);
            return BitConverter.ToString(hashBytes).Replace("-", "").ToLowerInvariant();
        }

        private bool _hasUnsavedChanges;

        private void Save()
        {
            if (SelectedFile == null || !File.Exists(SelectedFile.Path)) return;

            var enPath = SelectedFile.Path.Replace("\\zh-CN\\", "\\en-US\\");

            // 检查文件是否被修改
            var originalZhContent = File.ReadAllText(SelectedFile.Path);
            var originalEnContent = File.Exists(enPath) ? File.ReadAllText(enPath) : "";

            var currentZhHash = GenerateMD5(originalZhContent);
            var currentEnHash = GenerateMD5(originalEnContent);

            var zhDoc = XDocument.Load(SelectedFile.Path);
            XDocument enDoc;
            if (File.Exists(enPath))
            {
                enDoc = XDocument.Load(enPath);
            }
            else
            {
                enDoc = new XDocument(zhDoc);
                Directory.CreateDirectory(Path.GetDirectoryName(enPath));
            }

            var ns = zhDoc.Root?.GetDefaultNamespace();
            if (ns == null) return;

            foreach (var item in TranslationItems)
            {
                var zhElement = zhDoc.Descendants()
                    .FirstOrDefault(e => e.Attribute(XName.Get("Key", "http://schemas.microsoft.com/winfx/2006/xaml"))?.Value == item.Key);
                if (zhElement != null)
                {
                    zhElement.Value = item.ChineseText;
                }

                var enElement = enDoc.Descendants()
                    .FirstOrDefault(e => e.Attribute(XName.Get("Key", "http://schemas.microsoft.com/winfx/2006/xaml"))?.Value == item.Key);
                if (enElement != null)
                {
                    enElement.Value = item.EnglishText;
                }
                else
                {
                    var newElement = new XElement(ns + "String", new XAttribute(XName.Get("Key", "http://schemas.microsoft.com/winfx/2006/xaml"), item.Key), item.EnglishText);
                    enDoc.Root.Add(newElement);
                }
            }

            var result = MessageBox.Show("将覆盖源文件，是否继续？", "确认保存", MessageBoxButton.YesNo);
            if (result != MessageBoxResult.Yes) return;

            try
            {
                zhDoc.Save(SelectedFile.Path);
                enDoc.Save(enPath);
                _hasUnsavedChanges = false;
                MessageBox.Show("保存成功！", "提示", MessageBoxButton.OK);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存失败: {ex.Message}", "错误", MessageBoxButton.OK);
            }
        }
    }

    public class BaiduTranslationResult
    {
        [JsonProperty("trans_result")]
        public List<TranslationResult> TransResult { get; set; }
    }

    public class TranslationResult
    {
        [JsonProperty("src")]
        public string Src { get; set; }

        [JsonProperty("dst")]
        public string Dst { get; set; }
    }

    public class TranslationItem : BindableBase
    {
        private string _key;
        public string Key
        {
            get => _key;
            set => SetProperty(ref _key, value);
        }

        private string _chineseText;
        public string ChineseText
        {
            get => _chineseText;
            set
            {
                if (SetProperty(ref _chineseText, value))
                {
                    RaisePropertyChanged(nameof(IsModified));
                }
            }
        }

        private string _englishText;
        public string EnglishText
        {
            get => _englishText;
            set
            {
                if (SetProperty(ref _englishText, value))
                {
                    RaisePropertyChanged(nameof(IsModified));
                }
            }
        }

        private bool _hasUnsavedChanges;

        public bool IsModified
        {
            get
            {
                if (OriginalChinese == null || OriginalEnglish == null) return false;
                return ChineseText != OriginalChinese || EnglishText != OriginalEnglish;
            }
            set => SetProperty(ref _hasUnsavedChanges, value);
        }
        public string OriginalChinese { get; set; }
        public string OriginalEnglish { get; set; }
    }

    public class FileItem : BindableBase
    {
        private string _name;
        public string Name
        {
            get => _name;
            set => SetProperty(ref _name, value);
        }

        private string _path;
        public string Path
        {
            get => _path;
            set => SetProperty(ref _path, value);
        }

        private bool _isExpanded;
        public bool IsExpanded
        {
            get => _isExpanded;
            set => SetProperty(ref _isExpanded, value);
        }

        private ObservableCollection<FileItem> _children;
        public ObservableCollection<FileItem> Children
        {
            get => _children;
            set => SetProperty(ref _children, value);
        }

        public FileItem()
        {
            _children = new ObservableCollection<FileItem>();
        }
    }
}
